/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 * <p>
 * PmTeamController
 * 项目组成员
 * <p>
 * 修改纪录
 * 2020-05-12 版本：1.0 wushenghong 创建。
 *
 * @version 版本：1.0
 * @author 作者：wushenghong
 * 创建日期：2020-05-12
 */

package com.topscomm.pm.controller;

import com.topscomm.basic.exception.MessageException;
import com.topscomm.cbo.pojo.CboDeptEntity;
import com.topscomm.cbo.pojo.CboOrgEntity;
import com.topscomm.cbo.service.ICboDeptService;
import com.topscomm.cbo.service.ICboOrgService;
import com.topscomm.cbo.service.impl.CboDeptService;
import com.topscomm.pm.controller.auto.PmTeamControllerAuto;
import com.topscomm.pm.pojo.PmTeamEntity;
import com.topscomm.pm.utils.MisStringUtil;
import com.topscomm.pub.util.BaseUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.ITapService;
import com.topscomm.tap.common.TapSystemConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: wushenghong
 * @date: 2020-05-12
 * @description:项目组成员Controller
 * @modify:
 */
@RestController
@RequestMapping("pm/team")
public class PmTeamController extends PmTeamControllerAuto implements IPmTeamController {
    @Resource(name = "cboOrgService")
    private ICboOrgService cboOrgService;
    @Resource(name = "cboDeptService")
    private ICboDeptService cboDeptService;

    /**
     * @param paraMap
     * @return
     * @author: wushenghong
     * @date: 2020-05-12
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    protected String spellListSql(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" 1=1 ");
        if (paraMap.containsKey("qry_name")) {
            String value = paraMap.get("qry_name").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and username like '%{0}%' ", value);
        }
        if (paraMap.containsKey("qry_code")) {
            String value = paraMap.get("qry_code").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and usercode = '{0}' ", value);
        }
        if (paraMap.containsKey("qry_projectid")) {
            String value = paraMap.get("qry_projectid").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and projectid = {0} ", value);
        }
        // 控制参与人信息不可选负责人
        if (paraMap.containsKey("qry_notleadercode")) {
            String value = paraMap.get("qry_notleadercode").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and usercode ！= {0} ", value);
        }
        // 控制负责人信息不可选参与人
        if (paraMap.containsKey("qry_notparticipantcodes")) {
            String value = paraMap.get("qry_notparticipantcodes").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and usercode not in ({0}) ", value);
        }
        if (paraMap.containsKey("qry_role")) {
            String value = paraMap.get("qry_role").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and role = '{0}' ", value);
        }
        sql .appendSingle(this.spellingSqlForProject(paraMap, "PmTeam","projectid","id"));
        if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
        {
            String dataPession = service.getDataPermission(TapSystemConst.TapOperationTypeEnum.Select, "", this.getUserBean());
            if (StringUtil.isEmpty(dataPession)) {
                sql.appendSingle(" and " + MisStringUtil.createWhereByUsercodeFromProject(this.getUserBean().getUser(), "projectid", service.getDao().getTableName()));
            } else// 使用数据权限
            {
                sql.appendSingle(" and {0} ", dataPession);
            }
        }
        return sql.toString();
    }

    /**
     * @param paraMap
     * @return
     * @author: wushenghong
     * @date: 2020-05-12
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    @GetMapping(value = "/refList")
    public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
        super.refList(paraMap);
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            Query query = new Query(paraMap);
            // 添加有效过滤
            String sqlWhere =this.spellRefListSql(paraMap) + "and enabled = 1";
            int totalCount = ((ITapService)this.service).getCount(sqlWhere);
            List<Map<String, Object>> tempList = null;
            if (query.getPageSize() > 0) {
                tempList = ((ITapService)this.service).queryMapForPage(sqlWhere, query.getCurrentPage(), query.getPageSize(), query.getSidx(), query.getSord());
            } else {
                tempList = ((ITapService)this.service).queryMapByWhere(sqlWhere);
            }

            ((ITapService)this.service).setDispFields(tempList);
            Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
            return ResponseResult.ok(page);
        } catch (Exception var7) {
            return this.handleControllerException(var7);
        }
    }

    /**
     * @param paraMap
     * @description: 人员关联组织部门接口
     * @author: wushenghong
     * @date: 2020-05-12
     * @modify:
     */
    @GetMapping(value = "/queryOrgDeptByIds")
    public ResponseResult<Object> queryOrgDeptByIds(@RequestParam Map<String, Object> paraMap) {
        Map resultMap = new HashMap();
        String deptId = ConvertUtil.convertToString(paraMap.get("deptId"));
        String orgId = ConvertUtil.convertToString(paraMap.get("orgId"));
        CboDeptEntity cboDeptEntity = cboDeptService.queryById(deptId);
        if (cboDeptEntity == null) {
            resultMap.put("deptcode", "");
            resultMap.put("deptname", "");
        } else {
            resultMap.put("deptcode", cboDeptEntity.getCode());
            resultMap.put("deptname", cboDeptEntity.getFullname());
        }
        CboOrgEntity orgEntity = cboOrgService.queryById(orgId);
        if (orgEntity == null) {
            resultMap.put("orgcode", "");
            resultMap.put("orgname", "");
        } else {
            resultMap.put("orgcode", orgEntity.getCode());
            resultMap.put("orgname", orgEntity.getName());
        }
        return ResponseResult.ok(resultMap);
    }

    /**
     * @author: wudaliang
     * @date: 2021-02-20
     * @param: dataMap
     * @param: paraMap
     * @description:
     * @return: void
     * @modify:
     */
    @Override
    protected void beforeInsert(Map<String, Object> dataMap, Map<String, Object> paraMap)
        throws Exception {
        String projectid = paraMap.get("projectid").toString();
        String usercode = paraMap.get("usercode").toString();
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("projectid = '{0}' and usercode = '{1}'",projectid,usercode);
        List<PmTeamEntity> pmTeamEntities = this.service.queryByWhere(sql.toString());
        if(pmTeamEntities.size()>0){
            throw new MessageException("该项目组下已有该成员，不可重复添加！");
        }
    }
    /**
     * @author: wudaliang
     * @date: 2021-02-20
     * @param: dataMap
     * @param: paraMap
     * @description: 修正cbodept表中的数据
     * @return: void
     * @modify:
     */
    @GetMapping("/correctDept")
    protected void correctDept(Map<String, Object> dataMap, Map<String, Object> paraMap)
            throws Exception {
        // cbodeptcopy表中的数据为最新数据
        // cbodept表中缺失的数据,
        List<Map<String, Object>> list = this.service.selectExecute("SELECT *　　from CBODEPTCOPY WHERE not EXISTS(SELECT CODE FROM CBODEPT WHERE CBODEPTCOPY.CODE = CBODEPT.CODE ) ");
        for (Map<String, Object> item:list){
            item.remove("id");
            // 新建此部门
            CboDeptEntity cboDeptEntity = new CboDeptEntity();
            cboDeptEntity.convertFromMap(item);
            cboDeptService.insert(cboDeptEntity);
            //完善父级部门
            createParentId(item);
        }
    }

    // 递归，完善父级部门
    private void createParentId(Map<String, Object> deptMap){
        // 如果传入的部门的父级部门的code，在cbodept中存在，则递归停止
        // 先查询cbodeptcopy表中的父级部门的code
        List<Map<String, Object>> cbocopyList = this.service.selectExecute("select * from CBODEPTCOPY where id ='" + ConvertUtil.convertToString(deptMap.get("parentid")) + "'");
        // 查询是否有父级部门
        List<Map<String, Object>> cboList = cboDeptService.queryMapByWhere("code = '" + ConvertUtil.convertToString(cbocopyList.get(0).get("code")) + "'");
        if (cboList.size()>0)
        {
            return;
        }
        else {
            // 如果没有此部门则需要新建此部门
            CboDeptEntity cboDeptEntity = new CboDeptEntity();
            cbocopyList.get(0).remove("id");
            cboDeptEntity.convertFromMap(cbocopyList.get(0));
            cboDeptService.insert(cboDeptEntity);
            // 更新传入部门的父级部门id
            Map<String,Object> updateParam = new HashMap<>();
            updateParam.put("id",deptMap.get("id"));
            updateParam.put("parentid",cboDeptEntity.getId());
            cboDeptService.update(updateParam);
            // 递归调用
            createParentId(cbocopyList.get(0));
        }
    }
}

